<?php

//test excel export
function exportExcel($tableData) {
    vendor("PHPExcel.PHPExcel");
    vendor("PHPExcel.PHPExcel.IOFactory");
    //创建对象
    $excel = new \PHPExcel();
    //Excel表格式,这里简略写了8列
    $letter = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');

    if (isNullOrEmpty($tableData)) {
        $this->error('导出表格没有数据！');
    }
    //表头数组
    $tableheader = $tableData['header'];
    //填充表头信息
    $i = 0;
    foreach ($tableheader as $key => $value) {
        $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$value");
        $i++;
    }
    //表格数组
    $data = $tableData['list'];
    //填充表格信息
    for ($i = 2; $i <= count($data) + 1; $i++) {
        $j = 0;
        $item = $data[$i - 2];
        foreach ($tableheader as $key => $v) {
            $excel->getActiveSheet()->setCellValue("$letter[$j]$i", "$item[$key]");
            $j++;
        }
    }
    //创建Excel输入对象
    $write = new \PHPExcel_Writer_Excel5($excel);
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
    header("Content-Type:application/force-download");
    header("Content-Type:application/vnd.ms-execl");
    header("Content-Type:application/octet-stream");
    header("Content-Type:application/download");
    header('Content-Disposition:attachment;filename="testdata.xls"');
    header("Content-Transfer-Encoding:binary");
    $write->save('php://output');
}

//计算卡结束时间
function setEndTime($startTime, $buyType = 1, $termNum = 1) {
    if ($buyType == C('VIP_ORDER_BUY_TYPE.YEAR')) {
        $end = strtotime($startTime . '+' . $termNum . ' year');
    } elseif ($buyType == C('VIP_ORDER_BUY_TYPE.MONTH')) {
        $end = strtotime($startTime . '+' . $termNum . ' month');
    } elseif ($buyType == C('VIP_ORDER_BUY_TYPE.SEASON')) {
        $end = strtotime($startTime . '+' . ($termNum * 3) . ' month');
    }
    return date('Y-m-d H:i:s', $end);
}

function menu($typeid) {
    $menu_db = M('menu');          //获取栏目名称
    $menu = $menu_db->select();
    $this->assign('menu', $menu);
    foreach ($menu as $val) {
        if ($val['id'] == $typeid) {
            $menu2 = $val;
        }
    }
    return $menu;
}

function checkIsNeedReturn($minutes) {
    if ($minutes < C('MIN_MINUTES')) {
        return 1;
    } else if ($minutes >= C('MIN_MINUTES') && $minutes < C('HALF_MINUTES')) {
        return 0.5;
    }
    return 0;
}

function isNullOrEmpty($obj) {
    return (!isset($obj) || empty($obj) || $obj == null);
}

function getDefaultLanguageCategoryList() {
    $categoryList = D('category')->alias('c')
            ->join('left join l_language_content lc on lc.content_id = c.category_name')
            ->where('lc.language_id = ' . C('DEFAULT_LANGUAGE'))->field('lc.value,c.*')
            ->order('c.weight desc')
            ->select();

    return $categoryList;
}

/**
 * 全局获取验证码图片
 * 生成的是个HTML的img标签
 * @param string $imgparam <br>
 * 生成图片样式，可以设置<br>
 * length=4&font_size=20&width=238&height=50&use_curve=1&use_noise=1<br>
 * length:字符长度<br>
 * font_size:字体大小<br>
 * width:生成图片宽度<br>
 * heigh:生成图片高度<br>
 * use_curve:是否画混淆曲线  1:画，0:不画<br>
 * use_noise:是否添加杂点 1:添加，0:不添加<br>
 * @param string $imgattrs<br>
 * img标签原生属性，除src,onclick之外都可以设置<br>
 * 默认值：style="cursor: pointer;" title="点击获取"<br>
 * @return string<br>
 * 原生html的img标签<br>
 * 注，此函数仅生成img标签，应该配合在表单加入name=verify的input标签<br>
 * 如：&lt;input type="text" name="verify"/&gt;<br>
 */
function sp_verifycode_img($imgparam = 'length=4&font_size=20&width=238&height=50&use_curve=1&use_noise=1', $imgattrs = 'style="cursor: pointer;" title="点击获取"') {
    $src = U('Admin/Checkcode/index', $imgparam);
    $img = <<<hello
<img class="verify_img" src="$src" onclick="this.src='$src&time='+Math.random();" $imgattrs/>
hello;
    return $img;
}

/**
 * 验证码检查，验证完后销毁验证码增加安全性 ,<br>返回true验证码正确，false验证码错误
 * @return boolean <br>true：验证码正确，false：验证码错误
 */
function sp_check_verify_code() {
    $verify = new \Think\Verify();
    return $verify->check($_REQUEST['verify'], "");
}

/**
 * 检查权限
 * @param name string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
 * @param uid  int           认证用户的id
 * @param relation string    如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
 * @return boolean           通过验证返回true;失败返回false
 */
function sp_auth_check($uid, $name = null, $relation = 'or') {
    if (empty($uid)) {
        return false;
    }
    $iauth_obj = new \Common\Lib\iAuth();
    if (empty($name)) {
        $name = strtolower(MODULE_NAME . "/" . CONTROLLER_NAME . "/" . ACTION_NAME);
    }

    return $iauth_obj->check($uid, $name, $relation);
}

function get_current_admin_id() {
    return $_SESSION['ADMIN_ID'];
}

function sp_get_current_admin_id() {
    return get_current_admin_id();
}

function sp_is_user_login() {
    return !empty($_SESSION['user']);
}

function sp_get_current_user() {
    if (isset($_SESSION['user'])) {
        return $_SESSION['user'];
    } else {
        return false;
    }
}

function sp_update_current_user($user) {
    $_SESSION['user'] = $user;
}

function get_current_userid() {

    if (isset($_SESSION['user'])) {
        return $_SESSION['user']['id'];
    } else {
        return 0;
    }
}

function sp_get_current_userid() {
    return get_current_userid();
}

/**
 * URL组装 支持不同URL模式
 * @param string $url URL表达式，格式：'[模块/控制器/操作#锚点@域名]?参数1=值1&参数2=值2...'
 * @param string|array $vars 传入的参数，支持数组和字符串
 * @param string $suffix 伪静态后缀，默认为true表示获取配置值
 * @param boolean $domain 是否显示域名
 * @return string
 */
function leuu($url = '', $vars = '', $suffix = true, $domain = false) {
    $routes = sp_get_routes();
    if (empty($routes)) {
        return U($url, $vars, $suffix, $domain);
    } else {
        // 解析URL
        $info = parse_url($url);
        $url = !empty($info['path']) ? $info['path'] : ACTION_NAME;
        if (isset($info['fragment'])) { // 解析锚点
            $anchor = $info['fragment'];
            if (false !== strpos($anchor, '?')) { // 解析参数
                list($anchor, $info['query']) = explode('?', $anchor, 2);
            }
            if (false !== strpos($anchor, '@')) { // 解析域名
                list($anchor, $host) = explode('@', $anchor, 2);
            }
        } elseif (false !== strpos($url, '@')) { // 解析域名
            list($url, $host) = explode('@', $info['path'], 2);
        }

        // 解析子域名
        //TODO?
        // 解析参数
        if (is_string($vars)) { // aaa=1&bbb=2 转换成数组
            parse_str($vars, $vars);
        } elseif (!is_array($vars)) {
            $vars = array();
        }
        if (isset($info['query'])) { // 解析地址里面参数 合并到vars
            parse_str($info['query'], $params);
            $vars = array_merge($params, $vars);
        }

        $vars_src = $vars;

        ksort($vars);

        // URL组装
        $depr = C('URL_PATHINFO_DEPR');
        $urlCase = C('URL_CASE_INSENSITIVE');
        if ('/' != $depr) { // 安全替换
            $url = str_replace('/', $depr, $url);
        }
        // 解析模块、控制器和操作
        $url = trim($url, $depr);
        $path = explode($depr, $url);
        $var = array();
        $varModule = C('VAR_MODULE');
        $varController = C('VAR_CONTROLLER');
        $varAction = C('VAR_ACTION');
        $var[$varAction] = !empty($path) ? array_pop($path) : ACTION_NAME;
        $var[$varController] = !empty($path) ? array_pop($path) : CONTROLLER_NAME;
        if ($maps = C('URL_ACTION_MAP')) {
            if (isset($maps[strtolower($var[$varController])])) {
                $maps = $maps[strtolower($var[$varController])];
                if ($action = array_search(strtolower($var[$varAction]), $maps)) {
                    $var[$varAction] = $action;
                }
            }
        }
        if ($maps = C('URL_CONTROLLER_MAP')) {
            if ($controller = array_search(strtolower($var[$varController]), $maps)) {
                $var[$varController] = $controller;
            }
        }
        if ($urlCase) {
            $var[$varController] = parse_name($var[$varController]);
        }
        $module = '';

        if (!empty($path)) {
            $var[$varModule] = array_pop($path);
        } else {
            if (C('MULTI_MODULE')) {
                if (MODULE_NAME != C('DEFAULT_MODULE') || !C('MODULE_ALLOW_LIST')) {
                    $var[$varModule] = MODULE_NAME;
                }
            }
        }
        if ($maps = C('URL_MODULE_MAP')) {
            if ($_module = array_search(strtolower($var[$varModule]), $maps)) {
                $var[$varModule] = $_module;
            }
        }
        if (isset($var[$varModule])) {
            $module = $var[$varModule];
        }

        if (C('URL_MODEL') == 0) { // 普通模式URL转换
            $url = __APP__ . '?' . http_build_query(array_reverse($var));

            if ($urlCase) {
                $url = strtolower($url);
            }
            if (!empty($vars)) {
                $vars = http_build_query($vars);
                $url .= '&' . $vars;
            }
        } else { // PATHINFO模式或者兼容URL模式
            if (empty($var[C('VAR_MODULE')])) {
                $var[C('VAR_MODULE')] = MODULE_NAME;
            }

            $module_controller_action = strtolower(implode($depr, array_reverse($var)));

            $has_route = false;

            if (isset($routes[$module_controller_action])) {
                $urlrules = $routes[$module_controller_action];

                $empty_query_urlrule = array();

                foreach ($urlrules as $ur) {
                    $intersect = array_intersect($ur['query'], $vars);
                    if ($intersect) {
                        $vars = array_diff_key($vars, $ur['query']);
                        $url = $ur['url'];
                        $has_route = true;
                        break;
                    }
                    if (empty($empty_query_urlrule) && empty($ur['query'])) {
                        $empty_query_urlrule = $ur;
                    }
                }

                if (!empty($empty_query_urlrule)) {
                    $url = $empty_query_urlrule['url'];
                    foreach ($vars as $key => $value) {
                        if (strpos($url, ":$key") !== false) {
                            $url = str_replace(":$key", $value, $url);
                            unset($vars[$key]);
                        }
                    }
                    $url = str_replace(array("\d", "$"), "", $url);
                    $has_route = true;
                }

                if ($has_route) {
                    if (!empty($vars)) { // 添加参数
                        foreach ($vars as $var => $val) {
                            if ('' !== trim($val))
                                $url .= $depr . $var . $depr . urlencode($val);
                        }
                    }

                    $url = __APP__ . "/" . $url;
                }
            }

            if (!$has_route) {
                $module = defined('BIND_MODULE') ? '' : $module;
                $url = __APP__ . '/' . implode($depr, array_reverse($var));

                if ($urlCase) {
                    $url = strtolower($url);
                }

                if (!empty($vars)) { // 添加参数
                    foreach ($vars as $var => $val) {
                        if ('' !== trim($val))
                            $url .= $depr . $var . $depr . urlencode($val);
                    }
                }
            }


            if ($suffix) {
                $suffix = $suffix === true ? C('URL_HTML_SUFFIX') : $suffix;
                if ($pos = strpos($suffix, '|')) {
                    $suffix = substr($suffix, 0, $pos);
                }
                if ($suffix && '/' != substr($url, -1)) {
                    $url .= '.' . ltrim($suffix, '.');
                }
            }
        }

        if (isset($anchor)) {
            $url .= '#' . $anchor;
        }
        if ($domain) {
            $url = (is_ssl() ? 'https://' : 'http://') . $domain . $url;
        }

        return $url;
    }
}

function sp_get_routes($refresh = false) {
    $routes = F("routes");

    if ((!empty($routes) || is_array($routes)) && !$refresh) {
        return $routes;
    }
    $routes = M("AdminRoute")->where("status=1")->order("listorder asc")->select();
    $module_routes = array();
    $cache_routes = array();
    foreach ($routes as $er) {
        $full_url = $er['full_url'];

        // 解析URL
        $info = parse_url($full_url);

        $path = explode("/", $info['path']);
        if (count($path) != 3) {//必须是完整 url
            continue;
        }

        $module = strtolower($path[0]);

        // 解析参数
        $vars = array();
        if (isset($info['query'])) { // 解析地址里面参数 合并到vars
            parse_str($info['query'], $params);
            $vars = array_merge($params, $vars);
        }

        $vars_src = $vars;

        ksort($vars);

        $path = $info['path'];

        $full_url = $path . (empty($vars) ? "" : "?") . http_build_query($vars);

        $url = $er['url'];

        $cache_routes[$path][] = array("query" => $vars, "url" => $url);

        $module_routes[$module][$url] = $full_url;
    }
    F("routes", $cache_routes);
    $route_dir = SITE_PATH . "/data/conf/route/";
    foreach ($module_routes as $module => $routes) {

        if (!file_exists($route_dir)) {
            mkdir($route_dir);
        }

        $route_file = $route_dir . "$module.php";

        $route_ruels = array();

        file_put_contents($route_file, "<?php\treturn " . stripslashes(var_export($routes, true)) . ";");
    }

    return $cache_routes;
}

function formatDateString($time) {
    return substr($time, 0, 10);
}

function getCurrentDate() {
    return date('Y-m-d H:i:s');
}

function toSqlStartTime($time) {
    return $time . ' 00:00:00';
}

function toSqlEndTime($time) {
    return $time . ' 23:59:59';
}

function toSqlLike($str) {
    return '%' . $str . '%';
}

function toSqlIn($str) {
    return '(' . $str . ')';
}

function calculateDayGap($from, $to) {
   
    $day = ceil(($to-$from)/60/60/24);
    
    return $day;
    
}

function getEnumSelectWidget($enum, $name, $val = 0, $hasAll = 0) {

    $count = count($enum) / 2;
    $index = 0;

    $all = $hasAll == 1 ? '<option value="0">全部</option>' : '';

    $html = '<select class="js-example-basic-single" name=\'' . $name . '\'>' . $all;

    foreach ($enum as $key => $value) {

        if ($count == $index)
            break;

        $selected = '';

        if ($value == $val)
            $selected = 'selected="selected"';

        $html .= '<option value="' . $value . '" ' . $selected . '>' . $enum[$key . '_STRING'] . '</option>';

        $index++;
    }

    $html .= '</select>';

    return $html;
}

function getEnumString($enum, $value) {

    $key = array_search($value, $enum);

    $strKey = $key . '_STRING';

    return $enum[$strKey];
}

function createUuid($prefix = "") {    //可以指定前缀
    $str = md5(uniqid(mt_rand(), true));
    $uuid = substr($str, 0, 8) . '-';
    $uuid .= substr($str, 8, 4) . '-';
    $uuid .= substr($str, 12, 4) . '-';
    $uuid .= substr($str, 16, 4) . '-';
    $uuid .= substr($str, 20, 12);
    return $prefix . $uuid;
}

function getCategorySelectOptionHtml($categoryId = 0, $hasAll = 0) {
    $categoryList = D('Category')
        ->where(array("is_online"=>C("DEFAULT_YN.YES")))
        ->select();
    $html = '';
    if ($hasAll == 1)
        $html .= '<option value="0">全部</option>';

    foreach ($categoryList as $c) {

        $selected = '';

        if ($c['category_id'] == $categoryId)
            $selected = 'selected="selected"';

        $html .= '<option value="' . $c['category_id'] . '" ' . $selected . ' >' . $c['category_name'] . '</option>';
    }
    return $html;
}


if (!function_exists('array_column')) {
    function array_column($input, $columnKey, $indexKey = null) {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? true : false;
        $indexKeyIsNull = (is_null($indexKey)) ? true : false;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? true : false;
        $result = array();
        foreach ((array) $input as $key => $row) {
            if ($columnKeyIsNumber) {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
            } else {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : null;
            }
            if (!$indexKeyIsNull) {
                if ($indexKeyIsNumber) {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && !empty($key)) ? current($key) : null;
                    $key = is_null($key) ? 0 : $key;
                } else {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }
            $result[$key] = $tmp;
        }
        return $result;
    }
}

